package name.jasonfrank;

import java.io.File;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class CamCaptureDemoActivity extends Activity 
                                    implements OnClickListener {
	
	private static final String TAG = "CamCapture";
	private static final int CAM_PIC_REQUEST_CODE = 1492;
	private static final String PIC_BASE_NAME = "shareView_";
	private static final String PIC_EXTENSION = ".jpg";
	private static final String TIME_STAMP_PATTERN = "yyyy-MM-dd_HH-mm-ss_S";
	private String latestPicFullPath;
	// The main dir that the app will use to store each pic taken. This dir is the one
	//  that my Moto Electrify uses for default pics taken. Note that the Android docs
	//  explain that the "external" in this method does not necessarily refer to
	//  storage external to the phone (SD card), but rather storage that is distince 
	//  from the protected internal storage. See: http://developer.android.com/reference/android/os/Environment.html
	private static final String IMAGE_STORE_PATH = 
		                          Environment.getExternalStorageDirectory() + "/DCIM/Camera";
	private String emailTo   = "shareview972@gmail.com";
	private String emailFrom = "shareview972@gmail.com";
	private String emailPass = "somepassword";
	
	private Intent camIntent;
	
	//private Bitmap lastTakenBitmap;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    // Add click listener for the take pic btn
    View takePicBtn = findViewById(R.id.takePicBtn);
    takePicBtn.setOnClickListener(this);
      
  } ////////////// end onCreate() //////////////////

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		
			case R.id.takePicBtn:
				Log.i("Button", "'Take pic' button pressed.");
				
				// Construct the filename. Use a base (i.e, "shareView_"), plus timestamp.
				String timeStampStr = new SimpleDateFormat(TIME_STAMP_PATTERN).format(new Date());
				String picFilename = PIC_BASE_NAME + timeStampStr + PIC_EXTENSION;
				this.latestPicFullPath = IMAGE_STORE_PATH + "/" + picFilename;
						
				//Toast.makeText(this, "latestPicFullPath: " + this.latestPicFullPath, 
				//		           Toast.LENGTH_LONG).show();
				
				
				
				// Launch the camera to take and return an image
				this.camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				// the File constructor separates the path from the filename with the approp dir sep
				Uri picUri = Uri.fromFile(new File(IMAGE_STORE_PATH, picFilename));
				camIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
				
				startActivityForResult(camIntent, CAM_PIC_REQUEST_CODE );
				break;
				
		}
		
	} //////////// end onClick() ////////////////////////
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent retDataIntent) {
		
		if(requestCode == this.CAM_PIC_REQUEST_CODE) {
			if(resultCode == RESULT_OK ){
				String msg = "Camera app activity returned with RESULT_OK";
							//Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
				// From: http://mobile.tutsplus.com/tutorials/android/android-sdk-quick-tip-launching-the-camera/
				// "The image that is returned is appropriate for display on a small 
				//  device screen. It comes in directly to the results as an Android Bitmap object."
						//	Bitmap thumbnail = (Bitmap) retDataIntent.getExtras().get("data");
				ImageView imageView = (ImageView) findViewById(R.id.photoResultView);  
						//	imageView.setImageBitmap(thumbnail);  
				
				// Get a bitmap from the latest pic taken filename
				Bitmap latestPicBitmap = BitmapFactory.decodeFile(this.latestPicFullPath);
				imageView.setImageBitmap(latestPicBitmap); 
				
				if(latestPicBitmap == null ) {
					msg = "latestPicBitmap IS NULL !!!!!!!!!!!!";
					Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
					Log.i(TAG, msg);
				}
						//Log.i(TAG, "latestPicFullPath: " + this.latestPicFullPath);
						//Toast.makeText(this, "latestPicFullPath: " + this.latestPicFullPath,
						//		            Toast.LENGTH_LONG).show();

				sendEmail(this.latestPicFullPath);
			}
			// Handle cases where "the activity explicitly returned RESULT_CANCELED, 
			//  or didn't return any result, or crashed during its operation".
			else if(resultCode == RESULT_CANCELED ) {
				String msg = "Camera app activity failed!";
				Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(this, "Unknown result code returned from camera app", 
						                     Toast.LENGTH_SHORT).show();
			}
		} // end handling camera pic request return
		
		
	} ////////////// end onActivityResult() ////////////////
  
	
	private void sendEmail(String attachmentFullPath) {
		
		Mail m = new Mail(/* username: */ this.emailTo, this.emailPass); 
		 
    String[] toArr = {this.emailTo}; 
    m.setTo(toArr); 
    m.setFrom(this.emailFrom); 
    m.setSubject("shareview auto sent"); 
    m.setBody("Email body.... hello World!"); 
    
    try { 
    	if(attachmentFullPath != null) {
    		m.addAttachment(attachmentFullPath);
    	} 

      if(m.send()) { 
        Toast.makeText(this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
        Log.i(TAG, "Email was sent successfully.");
      } 
      else { 
        Toast.makeText(this, "Email was NOT sent.", Toast.LENGTH_LONG).show(); 
        Log.e(TAG, "Email was NOT sent."); 
      } 
    } catch(Exception e) { 
      Toast.makeText(this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
      Log.e(TAG, "Error: Could not send email.", e); 
    } 
		
	} ////////////// end sendEmail() /////////////////////////

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		//outState.put
	}
	
	protected void onRestoreInstanceState(Bundle inState) {
		super.onRestoreInstanceState(inState);
		
	}
	
  
  
} ////////////////////////// end class //////////////////////